import { ReactElement, useRef, useState, useEffect, useContext, RefObject } from 'react'
import { Modal, Form, Select, FormInstance } from 'antd'
import { awaitWrap } from '@src/assets/js/tool'
import { getPersonListReuqest, OptionSchame } from './ajax'
import { Context } from '../../../../context'

const { Item } = Form
const { Option } = Select

async function initTree (setOptions: (v: OptionSchame[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonListReuqest())
  if (e === null && d !== null) {
    setOptions(d)
  }
}

function selectPerson (v: string, options: OptionSchame[], formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  const o = options.find(li => li.value === v)
  if (o !== undefined && c !== null) {
    c.setFieldsValue({
      processer: o.title
    })
  }
}

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props): ReactElement {
  const { updateCaseDetail, caseDetail } = useContext(Context)
  const formRef = useRef<FormInstance>(null)
  const [options, setOptions] = useState<OptionSchame[]>([])
  useEffect(() => {
    initTree(setOptions).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (visible && caseDetail !== null && c !== null) {
      c.setFieldsValue({ processerid: caseDetail.processerid, processer: caseDetail.processer })
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [caseDetail, formRef, visible])
  return (
    <Modal title='修改办案秘书' visible={visible} onOk={() => formRef.current?.submit()} onCancel={hide} maskClosable>
      <Form ref={formRef} labelCol={{ flex: '80px' }} onFinish={d => updateCaseDetail(d)}>
        <Item name='processer' noStyle><span /></Item>
        <Item name='processerid' label='办案秘书' rules={[{ required: true, message: '办案秘书不能为空' }]}>
          <Select placeholder='请选择' onChange={(v: string) => selectPerson(v, options, formRef)}>
            {options.map((li, i) => {
              return <Option key={i} value={li.value}>{li.title}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
